package com.arges.controller;

import com.arges.baen.BatchUrlBean;
import com.arges.baen.BatchUrlVO;
import com.arges.pojo.Result;
import com.arges.service.IvideoService;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author fanweitao
 * @date 2022/12/08
 */
@Validated
@RestController
public class VideoController {


    @Autowired
    private IvideoService ivideoService;


    @Autowired
    private RestTemplate restTemplate;

    /**
     * 批量获取通道实时流URL地址
     */
    @PostMapping(value = "/devices/channels/getVideoRealtimeUrls")
    public Result getVideoRealtimeUrls(@RequestBody @Valid List<BatchUrlBean> batchUrlBeans) {

        try {
            System.out.println("getVideoRealtimeUrls BatchUrlBean :" + batchUrlBeans.toString());
            for (int i = 0; i < batchUrlBeans.size(); i++) {
                if (batchUrlBeans.get(i).getProtocolType() == 6 && StringUtils.isBlank(batchUrlBeans.get(i).getPlugId())) {
                    throw new Exception("[getVideoRealtimeUrls.batchUrlBeans[" + i + "].streamUuid] plugId is null");
                }
            }
            List<BatchUrlVO> resultList = batchUrlBeans.parallelStream().map(item -> {
                String streamUrl = "";
                try {
                    String batchUrl = ivideoService.getBatchUrl(item);
                    ResponseEntity<String> responseEntity = restTemplate.getForEntity(batchUrl, String.class);
                    String entityBody = responseEntity.getBody();

                    if (!entityBody.contains("data")) {
                        throw new RuntimeException(entityBody);
                    }
                } catch (Exception e) {
                    System.out.println("getVideoRealtimeUrls BatchUrlBean :" + item.toString());
                }
                // 返回数据对象 batchUrlVO
                BatchUrlVO batchUrlVO = new BatchUrlVO();
                batchUrlVO.setDeviceCode(item.getDeviceCode());
                batchUrlVO.setChannelCode(item.getChannelCode());
                batchUrlVO.setStreamUuid(item.getStreamUuid());
                batchUrlVO.setStreamUrl(streamUrl);
                return batchUrlVO;
            }).collect(Collectors.toList());
            System.out.println("getVideoRealtimeUrls resultList :" + resultList.toString());
            return Result.success(resultList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(null);

    }

}
